//
//  CameraListViewController.m
//  OST
//
//  Created by mac on 13-7-6.
//  Copyright (c) 2013年 mac. All rights reserved.
//

#import "CameraListViewController.h"
#import "DeviceListCell.h"
#import "CameraViewController.h"
#import "WisCameraControlViewController.h"
#import "AddCemeralViewController.h"
#import "Common.h"
#import "CameraData.h"
#import "wis.h"
#import "Utitlity.h"
#import "ChangeInfoDialog.h"
#import "MMProgressHUD.h"

@interface CameraListViewController ()<loadPageCameraDelegate,DeviceListCellDelegate,UIActionSheetDelegate,changeDataDicDelegate>
{
    NSString *ipUrl;
    //NSNumber *port;
    NSDictionary *rowData;
    UIButton *right;
    BOOL isEditing;
    NSMutableArray *resultItem;
    NSMutableArray *tcpResult;//tcp
}

@end

@implementation CameraListViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    closeNextPage = YES;
    threadLoadData = NO;
    BottomView *bottomView = [self addBottomView];
    bottomView.btn_all_power.hidden = NO;
    [bottomView.btn_all_power addTarget:self action:@selector(addBtnDevice) forControlEvents:UIControlEventTouchUpInside];
    dataTableView.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - bottomView.frame.size.height);
    self.title =@"Surveillance";
    isEditing = NO;

    [self refreshData];
    
    [self requestGetRoomList];
}

- (void)addBtnDevice
{
    UIActionSheet *cameraActSht = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"添加摄像头",@"移除摄像头", nil];
    [cameraActSht showInView:self.view];
}

-(void)deleteCamera
{
//    [dataTableView setEditing:NO animated:YES];
//    [right setHidden:YES];
}

-(CGFloat)rowHeight
{
    return 76;
}

- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	NSUInteger row=[indexPath row];
    static NSString *DeviceListCellIdentifier = @"DeviceListCellIdentifier";
    DeviceListCell *cell = (DeviceListCell*)[dataTableView dequeueReusableCellWithIdentifier:DeviceListCellIdentifier];
    if (cell==nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"DeviceListCell" owner:self options:nil]lastObject];
        [cell initView];
       
        cell.btn_refresh.hidden = YES;
        cell.icon.highlightedImage = [UIImage imageNamed:@"icon_camera_selected"];
        cell.delegate = self;
        cell.remoteChnageBtn .hidden = YES;
        cell.changeBtn.hidden = NO;
    }
    cell.delegate = self;
    rowData = [self.rows objectAtIndex:row];
    NSMutableDictionary *muDic = [rowData mutableCopy];
    NSString *strUuid = [[GlobalService sharedInstance].curOperationDeviceUUID stringByReplacingOccurrencesOfString:@":" withString:@""];
    NSString *zidStr = muDic[@"CID"];
    NSString *appStr = [NSString stringWithFormat:@"%@c%@",strUuid,zidStr];
    [muDic setObject:appStr forKey:@"uuid"];
    [cell setCameraCellData:muDic];
    return cell;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger row=[indexPath row];
    rowData = [self.rows objectAtIndex:row];
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        ipUrl = [Utitlity judgeipUrl];
        
        NSString *cidStr = [rowData objectForKey:@"CID"];
        
        NSString *removeCameraStr = [NSString stringWithFormat:@"http://%@/cgi-bin/IpCamera.cgi?OP=2&CID=%@",ipUrl,cidStr];
        [Utitlity commonHTTPMethod:removeCameraStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            NSLog(@"responeObject:%@",responseObject);
            
            if ([responseObject[@"state"] isEqualToString:@"Success"])
            {
                [self.rows removeObject:rowData];
                [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationTop];
                [dataTableView setEditing:NO animated:YES];
            }
            else
            {
                [MMProgressHUD dismissWithError:@"删除失败"];
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            
            NSLog(@"error:%@",error);
        }];
    }
    
}

-(void)didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger row=[indexPath row];
    rowData = [self.rows objectAtIndex:row];
    
    /*CameraViewController *camera = [[CameraViewController alloc]initWithNibName:@"CameraViewController" bundle:nil];
    camera.title = [rowData objectForKey:@"Alias"];
    camera.camConfig = rowData;
    [self.navigationController pushViewController:camera animated:YES];
    */
    NSLog(@"camerlist rowData: %@", rowData.description);
    NSString *camURL = [rowData objectForKey:@"VideoStream"];
    if([camURL length] != 0)
    {
        WisCameraControlViewController * controller = [[WisCameraControlViewController alloc] initWithNibName:@"WisCameraControlViewController" bundle:nil];
        controller.camURL = camURL;
        controller.devUUID = [GlobalService sharedInstance].curOperationDeviceUUID;
        controller.cID = rowData[@"CID"];
        [self.navigationController pushViewController:controller animated:YES];
    }

}

-(NSArray *)loadPageData:(int)page
{
    ipUrl = [Utitlity judgeipUrl];
    
    [activity startAnimating];
    if (ipUrl)
    {
        resultItem = [[NSMutableArray alloc] init];
        NSString *urlStr = [NSString stringWithFormat:@"http://%@/cgi-bin/IpCamera.cgi?OP=3&Remote=0",ipUrl];
        
        [Utitlity commonHTTPMethod:urlStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            [activity stopAnimating];
            
            NSLog(@"camlistVC loadPageData");
            if (!responseObject) return;
            NSDictionary *retJsonData = responseObject;
            NSLog(@"camlist %@", retJsonData.description);
            if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
                
//                NSMutableArray *result = [NSMutableArray array];
                NSArray *devList = [retJsonData objectForKey:@"data"];
                for (NSDictionary *dict in devList)
                {
                    NSDictionary *item = dict;
                /*
                    NSString *videoStreamURL = dict[@"VideoStream"];
                   
                    NSRange range = [videoStreamURL rangeOfString:@"url=http://"];
                    if (range.location != NSNotFound) {
                        
                        NSRange replaceRange = NSMakeRange(range.location + range.length, 10);
                        videoStreamURL = [videoStreamURL stringByReplacingCharactersInRange:replaceRange withString:@"192.168.1.163:83"];
                        NSMutableDictionary *data = [NSMutableDictionary dictionaryWithDictionary:dict];
                        data[@"VideoStream"] = videoStreamURL;
                        item = data;
                    }
                    */
                    [resultItem addObject:item];
                }
                //self.rows = result;
                [super doneLoadingTableViewData:resultItem];
                //[dataTableView reloadData];
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
        }];
    }
    else
    {
        [[CMDDataProcessor sharedInstance] sendCMDId:WIS_CMD_V2_CMD_CAM_LIST_GET cmdLength:32 withData:(void *)[[[GlobalInfo sharedInstance] getUniqueID] UTF8String] callRecivedBlock:^(id data) {
            
            [activity stopAnimating];
            NSLog(@"camlist sendCMDId");
            if (!data) return;
            NSDictionary *retJsonData = data;
            NSLog(@"camlist sendCMDId %@", retJsonData.description);
            if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
                
                tcpResult = [NSMutableArray array];
                NSArray *devList = [retJsonData objectForKey:@"data"];
                
                for (NSDictionary *dict in devList) {
                    [tcpResult addObject:dict];
                }
                
                //self.rows = result;
                [super doneLoadingTableViewData:tcpResult];
                //[dataTableView reloadData];
            }
            
        }];
    }
    /*
    [[CameraData sharedInstance]getDataWithDataRecivedBlock:^(id data) {
        [activity stopAnimating];
        [super doneLoadingTableViewData:data];
    }];
    */
    return nil;
}

- (void)deleteCameraCid:(int)cid
{
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {
        NSString *urlStr = [NSString stringWithFormat:@"http://%@/cgi-bin/IpCamera.cgi?OP=2&CID=%d",ipUrl,cid];
        [Utitlity commonHTTPMethod:urlStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            if ([[responseObject[@"state"] lowercaseString] isEqualToString:@"success"])
            {
                [self loadPageData:1];
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
        }];
    }
    
}

#pragma mark - ADDddelegate

- (void)loadCameraList
{
    [self loadPageData:1];
}
//
- (void)changeCameraInfo:(NSDictionary *)data cell:(DeviceListCell *)cell
{
    ChangeInfoDialog  *yijianview = [[[NSBundle mainBundle] loadNibNamed:@"ChangeInfoDialog" owner:self options:nil]lastObject];
    [yijianview initView];
    yijianview.delegate = self;
    [yijianview setRoomDataList:_roomDataList];
    [yijianview setCameraData:data cell:cell];
    [yijianview pageStart];
}

- (void)changeInfoDialogWithData:(NSDictionary *)dic changeToRoom:(RoomItemModel *)changeRoomData {
    
    for (NSInteger i=0; i<self.rows.count; i++) {
        NSDictionary *data = self.rows[i];
        if ([data[@"CID"] integerValue] == [dic[@"CID"] integerValue]) {
            
            NSNumber *rooId = dic[@"Room"];
            NSMutableDictionary *reDic = [data mutableCopy];
            reDic[@"Room"] = rooId;
            [self.rows replaceObjectAtIndex:i withObject:reDic];
            [dataTableView reloadData];
            break;
        }
    }
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0)
    {
        AddCemeralViewController *addVC = [[AddCemeralViewController alloc] init];
        addVC.delegate  = self;
        [self.navigationController pushViewController:addVC animated:YES];
    }
    else if(buttonIndex ==1)
    {
        [right setHidden:YES];
        [dataTableView setEditing:YES animated:YES];
    }
}

- (void)changeCameraDic:(NSDictionary *)dic
{
    ipUrl = [Utitlity judgeipUrl];
    
//    for (int i = 0; i < [tcpResult count];i++)
//    {
//        NSDictionary *proDic = [tcpResult objectAtIndex:i];
//        if([dic[@"CID"] isEqual:proDic[@"CID"]])
//        {
//            NSMutableDictionary *mcDic = [dic mutableCopy];
//            [tcpResult replaceObjectAtIndex:i withObject:mcDic];
//        }
//    }
//    [MMProgressHUD showWithStatus:@"修改名字中...."];
//    [MMProgressHUD dismissWithSuccess:@"修改名字成功"];
//    
//    [super doneLoadingTableViewData:tcpResult];
   
    if (ipUrl)
    {
        for (int i = 0; i < [resultItem count];i++)
        {
            NSDictionary *proDic = [resultItem objectAtIndex:i];
            if([dic[@"CID"] isEqual:proDic[@"CID"]])
            {
                NSMutableDictionary *mcDic = [dic mutableCopy];
                [resultItem replaceObjectAtIndex:i withObject:mcDic];
            }
        }
        [MMProgressHUD showWithStatus:@"修改名字中...."];
        [MMProgressHUD dismissWithSuccess:@"修改名字成功"];
        
        [super doneLoadingTableViewData:resultItem];
    }
    else
    {
        [MMProgressHUD showWithTitle:@"修改名称错误" status:@"只能在局域网内进行修改"];
        [MMProgressHUD dismissAfterDelay:1];
    }

}

@end
